<?php
/**
 * 执行升级脚本
 * php db/upgrade.php 执行sql
 * php db/upgrade.php echo 1504077982 输出 sql, 可以指定版本
 */
error_reporting(0);
PHP_SAPI == 'cli' or exit('use cli');
chdir(__DIR__ . "/../..");

function query ($sqlOrConfig)
{
    static $resConfig;
    if (is_array($sqlOrConfig))
    {
        $resConfig = $sqlOrConfig;
        $link = mysql_connect($resConfig['DB_HOST'] . ':' . $resConfig['DB_PORT'], $resConfig['DB_USER'], $resConfig['DB_PWD'], true) or exit('Can not connect to db host');
        mysql_query("use " . $resConfig['DB_NAME']) or exit('Can not use db');
        mysql_query('set names utf8');
        return true;
    }
    
    $sql = @str_replace('@p_', $resConfig['DB_PREFIX'], $sqlOrConfig);
    $res = mysql_query($sql);
    if (is_bool($res))
    {
        return $res;
    }
    
    $arr = array();
    while ($row = mysql_fetch_array($res, MYSQL_ASSOC))
    {
        $arr[] = $row;
    }
    return $arr;
}

$rootConfig = require 'config.php';
file_exists('config.dev.php') and $rootConfig = array_merge($rootConfig, require 'config.dev.php');
file_exists('config.product.php') and $rootConfig = array_merge($rootConfig, require 'config.product.php');

query($rootConfig);

$sqlFiles = glob(__DIR__ . "/sql/*.sql") ?  : [];
sort($sqlFiles);

$versionName = 'DB_UPDATE_VERSION';
$versionRecord = query("SELECT value FROM @p_config WHERE name='$versionName'");
$version = $versionRecord ? $versionRecord[0]['value'] : 0;

// 指定版本
if($argv[2]){
    $version = $argv[2];
}

$sqls = [];
foreach ($sqlFiles as $_file)
{
    $_time = substr($_file, - 14, - 4);
    if ($_time > $version)
    {
        $_sqls = explode(";\n", file_get_contents($_file));
        foreach ($_sqls as $_sql)
        {
            $sqls[] = trim(trim($_sql), ';') . ';';
        }
        $version = $_time;
    }
}

$sqls or exit('no change');
$argv[1] == 'echo' and exit(implode("\n", $sqls) . "\n");
$res = [];
$status = true;
foreach ($sqls as $_sql)
{
    $_res = $_sql . "\n# result : ";
    $_res .= query($_sql) === false ? "ERROR : (" . mysql_errno() . ") " . mysql_error() : 'OK';
    $_res .="\n";
    $res[] = $_res;
}
$versionRecord or query("INSERT INTO @p_config (type,title,`group`,extra,remark,create_time,update_time,status,name,value,sort) VALUES(0,'db 版本','0','',''," . time() . "," . time() . ",1,'$versionName','',0)");
$status and query("UPDATE @p_config SET value='$version',update_time=" . time() . " WHERE name='$versionName'");
$dir = "Data/Backup/Db/";
file_exists($dir) or mkdir($dir,0777,true) and chmod($dir, 0777);
file_put_contents($dir.time().'.log', implode("\n", $res));
exit(implode("\n", $res) . "\n");
